function main( ui ) {

  var json = ui.getQueryParameters().getFirst("json");
  
  if ( json == null ){
        var ex = "{ exception: { message: 'no param provided'} }";
        return ex;
  }
 /* 
  var jsonObject = new JSONObject( );
  jsonObject.put('userId','casolla.alessandro@gmail.com');
  jsonObject.put('deviceId','123456');
  
*/
   var jsonObject = new JSONObject( json );
 // return jsonObject;
  return getUser( jsonObject );
}


function getUser(jsonObject) {

  var records = new JSONArray();
 
  var cmd = "select t from UserEntity t where t.userId=:userId";
  
  
  EntityManager.find(  
  cmd,  
  jsonObject,
  function(result) {
      
      for( var i = 0; i < result.size() ; ++i ) {
        
        records.put( JSONObject.wrap(result.get(i)) );
      }
      
    });
    
  var result = new JSONObject();
  result.put( "records", records );
  
  var deviceIdCloud = records.get(0).get('deviceId');
  var deviceIdDevice = '';
  
  
  
  /////////
  /*
     var u = new UserEntity();
      records.get(0).copyTo( u );
      u.deviceId = '';
      u.name='i5bgt22s88n4i8ud0s3k9c46fk@group.calendar.google.com';    
  EntityManager.storeUser( u );
      return u;
  */
  /////////
  
  
  
  try {
     deviceIdDevice = jsonObject.get('deviceId')
        } catch ( e){
          throw 'ERROR No device Id provided';
        }
  
  if ( deviceIdDevice.length == 0 )
        throw 'ERROR Device Id invalid';
  
  if ( deviceIdCloud.length() > 0 && !deviceIdCloud.equals(deviceIdDevice )){
    throw 'ERROR Account already registered, cloud : ' + deviceIdCloud + ' device : ' + deviceIdDevice;
       } 
  if ( deviceIdCloud.length() == 0 && deviceIdDevice.length() > 0 ){
      
      var u = new UserEntity();
      records.get(0).copyTo( u );
      u.deviceId = deviceIdDevice;
      EntityManager.storeUser( u );
  }
  
  var accObj = new JSONObject();
  accObj.put('accUser','acasolla');
  accObj.put('accPsw','password');
  
  result.put( "account",accObj);
  
  return result.toString() ;

}

